<?php
/**
 * 账号运营辅导控制器
 */
namespace Beerus\Modules\DesignerInfoLib\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\DesignerInfoLib\OperateInfo as mOperateInfo;
use Doraemon\model\Operator as mOperator;
use Doraemon\model\DesignerAuth as mDesignerAuth;
use Encore\Admin\Facades\Admin;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;
use Doraemon\pockets\constInterface\DesignerInfoLib\OperateInfo as iOperateInfo;
use Doraemon\model\DesignerInfoLib\DesignerOperateHelpPageDayCollect as mDesignerOperateHelpPageDayCollect;
use Doraemon\model\DesignerInfoLib\StageTask as mStageTask;
use Doraemon\model\DesignerInfoLib\OperateLog as mOperateLog;
use Doraemon\model\Designer\RenewIntentionLog as mRenewIntentionLog;

class GuiderController extends Controller implements iOperateInfo {

    const PAGE_SIZE = 5;

    // 账号运营辅导列表
    public function index(Request $request, Content $content) {
        Admin::script(self::setScript());
        $params = $request->all();
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = self::buildCondition($params);
        $condition['auth_status'] = self::AUTH_STATUS_ONLINE;
        $total = mOperateInfo::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        $lists = mOperateInfo::select('*', $condition);

        $operatorList = mOperator::getOperatorWithShowNameList();
        $operators = array_combine(array_column($operatorList, 'id'), array_column($operatorList, 'operator_show_name'));
        $operators[0] = '未绑定运营';

        // 获取任务详情列表
        $taskInfoList = mStageTask::getTaskList();
        $taskInfoMap = array_column($taskInfoList, 'task_info', 'id');

        self::formatList($lists);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        Admin::style('
            #filter-box .col-sm-3{padding-left:0;padding-right:2px}
            #filter-box .col-sm-9{padding-left:2px;padding-right:0px}
        ');

        Admin::script(
            <<<EOF
            $('#filter-box > form > div.row > div:nth-child(3) > div > div > div:nth-child(2) > label').removeClass('col-sm-2').addClass('col-sm-3');
            $('#filter-box > form > div.row > div:nth-child(3) > div > div > div:nth-child(2) > div').removeClass('col-sm-8').addClass('col-sm-9');
            $('#filter-box > form > div.row > div:nth-child(3) > div > div > div:nth-child(3) > label').removeClass('col-sm-2').addClass('col-sm-3');
            $('#filter-box > form > div.row > div:nth-child(3) > div > div > div:nth-child(3) > div').removeClass('col-sm-8').addClass('col-sm-9');
            $('.total_auth_year_start').attr('placeholder', '最多小数点后两位');
            $('.total_auth_year_end').attr('placeholder', '最多小数点后两位');
            $('.total_auth_year_end').after('<span class="input-group-addon">年</span>');
            $('.cur_renewal_rate_end').after('<span class="input-group-addon">%</span>');
        EOF);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $operators, $taskInfoMap) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->disableCreateButton();

                $grid->filter(function (Grid\Filter $filter) use ($operators) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 3, function ($filter) use ($operators) {
                        $filter->equal('keyword', 'UID/昵称')->placeholder('请输入uid或者昵称');
                        $filter->in('main_area_code', '地区(多选)')->multipleSelect(Region::getProvincesList());
                        $filter->in('operator_id', '对接运营(多选)')->multipleSelect($operators);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('cur_stage', '当前阶段')->select(self::STAGE_TXT_MAP);
                        $filter->equal('cur_stage_task_done_status', '阶段任务')->select(self::TASK_DONE_TXT_MAP);
                        $filter->equal('login_status', '登录状态预警')->select(self::LOGIN_STATUS_FLAG_TXT_MAP);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('consult_status', '咨询状态预警')->select(self::CONSULT_STATUS_FLAG_TXT_MAP);
                        $filter->between('total_auth_year', '累计认证时长')->placeholder('小数点两位');
                        $filter->between('cur_renewal_rate', '最新预估续费率')->placeholder('小数点三位');
                    });

                    $filter->expand();
                });
                $grid->column('uid', 'UID')->width(100);
                $grid->column('user_info', '用户基础信息')->display(function () use ($operators) {
                    $userInfo = [
                        '<strong>[昵称]: </strong>' . $this->nick,
                        '<strong>[对接运营]: </strong>' . $operators[$this->operator_id],
                        '<strong>[认证类型]: </strong>' . mDesignerAuth::DESIGNER_TYPE[$this->auth_type],
                        '<strong>[累计认证时长]: </strong>' . number_format($this->total_auth_year/10, 1) . '年',
                        '<strong>[主要服务地区]: </strong>' . $this->main_area_name ?? '未设置',
                        '<strong>[认证到期时间]: </strong>' . date('Y-m-d H:i:s', $this->auth_end_time),
                    ];
                    return implode("<br>", $userInfo);
                })->width(170);
                $grid->column('task_info', '任务')->display(function () use ($taskInfoMap) {
                    $uid = $this->uid;
                    $stageList = [];
                    $stageTaskInfo = json_decode($this->stage_task_info, true);
                    array_multisort(array_column($stageTaskInfo, 'task_no'), SORT_DESC, $stageTaskInfo);
                    foreach ($stageTaskInfo as $item) {
                        $stageName = self::STAGE_TXT_MAP[$item['stage_id']];
                        $stageItem = "<strong title='{$taskInfoMap[$item['task_id']]}'>[{$stageName}-任务{$item['task_no']}]:</strong>";
                        if ($item['task_no'] == self::TASK_NO_ONE) {
                            $doneHtml = $item['task_status']==self::TASK_DONE ? "selected='selected'" : '';
                            $notDoneHtml = $item['task_status']==self::TASK_NOT_DONE ? "selected='selected'" : '';
                            $stageItem .= "<select class='task-one-select' data-uid='{$uid}'><option value='2' {$doneHtml}>达标</option><option value='1' {$notDoneHtml}>未达标</option></select>";
                        } else if ($item['task_no'] == self::TASK_NO_FIVE) {
                            if ($item['task_status'] == self::TASK_NOT_DONE) {
                                $stageItem .= '续费意愿-待录入';
                            } else {
                                $stageItem .= '续费意愿-'.mRenewIntentionLog::INTENTION_LEVEL_LIST[$item['task_data']['intention_level']];
                            }
                        } else if ($item['task_no'] == self::TASK_NO_SIX) {
                            if ($item['task_status'] == self::TASK_NOT_DONE) {
                                $stageItem .= '续费意愿-'.($item['task_data']['intention_level']? mRenewIntentionLog::INTENTION_LEVEL_LIST[$item['task_data']['intention_level']] : '待录入').';续费结果-'.($item['task_data']['is_renew'] ? '已续费' : '未续费');
                            } else {
                                $stageItem .= '续费意愿-'.mRenewIntentionLog::INTENTION_LEVEL_LIST[$item['task_data']['intention_level']].';续费结果-'.($item['task_data']['is_renew'] ? '已续费' : '未续费');
                            }
                        } else {
                            $stageItem .= self::TASK_DONE_TXT_MAP[$item['task_status']];
                        }
                        $stageList[] = $stageItem;
                    }
                    return implode("<br>", $stageList);
                })->width(320);
                $grid->column('consult_info', '各月均咨询数')->display(function () {
                    $consultCntTxt = [];
                    if ($this->consult_cnt !== '') {
                        $consultCnt = explode(',', $this->consult_cnt);
                        foreach ($consultCnt as $key => $cnt) {
                            $month = $key+1;
                            $consultCntTxt[] = "<strong>[{$month}个月]: </strong>{$cnt}";
                        }
                    }
                    $consultCntTxt = array_reverse($consultCntTxt);
                    return '<div style="height: 130px;overflow: scroll">'.implode('<br>', $consultCntTxt).'</div>';
                })->width(150);
                $grid->column('comment_info', '各月均评论数')->display(function () {
                    $commentCntTxt = [];
                    if ($this->comment_cnt !== '') {
                        $commentCnt = explode(',', $this->comment_cnt);
                        foreach ($commentCnt as $key => $cnt) {
                            $month = $key+1;
                            $commentCntTxt[] = "<strong>[{$month}个月]: </strong>{$cnt}";
                        }
                    }
                    $commentCntTxt = array_reverse($commentCntTxt);
                    return '<div style="height: 130px;overflow: scroll">'.implode('<br>', $commentCntTxt).'</div>';
                })->width(150);
                $grid->column('fans_info', '各月均粉丝数')->display(function () {
                    $fansCntTxt = [];
                    if ($this->fans_cnt !== '') {
                        $fansCnt = explode(',', $this->fans_cnt);
                        foreach ($fansCnt as $key => $cnt) {
                            $month = $key+1;
                            $fansCntTxt[] = "<strong>[{$month}个月]: </strong>{$cnt}";
                        }
                    }
                    $fansCntTxt = array_reverse($fansCntTxt);
                    return '<div style="height: 130px;overflow: scroll">'.implode('<br>', $fansCntTxt).'</div>';
                })->width(150);
                $grid->column('renewal_rate_info', '预估续费概率')->display(function () {
                    $renewProTxt = [];
                    if ($this->renew_pro !== '') {
                        $renewPro = explode(',', $this->renew_pro);
                        foreach ($renewPro as $key => $pro) {
                            $month = $key+1;
                            $renewProPercent = round($pro, 3) * 100 . '%';
                            $renewProTxt[] = "<strong>[{$month}个月]: </strong>{$renewProPercent}";
                        }
                    }
                    $renewProTxt = array_reverse($renewProTxt);
                    return '<div style="height: 130px;overflow: scroll">'.implode('<br>', $renewProTxt).'</div>';
                })->width(150);
                $grid->column('latest_info', '最近30天数据')->display(function () {
                    $userInfo = [
                        '<strong>[登&nbsp;&nbsp;录&nbsp;&nbsp;天&nbsp;数]: </strong>' . $this->login_cnt_30,
                        '<strong>[登&nbsp;&nbsp;录&nbsp;&nbsp;状&nbsp;态]: </strong>' . $this->login_status_30,
                        '<strong>[咨&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;询&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;量]: </strong>' . $this->consult_cnt_30,
                        '<strong>[咨&nbsp;&nbsp;询&nbsp;&nbsp;状&nbsp;态]: </strong>' . $this->consult_status_30,
                        '<strong>[咨询未读数]: </strong>' . $this->consult_unread_cnt_30,
                        '<strong>[交&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;互&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数]: </strong>' . $this->action_cnt_30,
                        '<strong>[被&nbsp;&nbsp;交&nbsp;&nbsp;互&nbsp;数]: </strong>' . $this->beaction_cnt_30,
                    ];
                    return implode("<br>", $userInfo);
                })->width(150);
                $grid->column('sign_cnt', '最近认证周期內签单数')->editable()->width(140);
                $grid->column('operator_guide', '运营辅导动作')->display(function () {
                    $designerUid = $this->uid;
                    $renewPro = explode(',', $this->renew_pro);
                    $monthNum = count($renewPro);
                    if (!empty($this->oper_guide_actions)) {
                        $operGuideActions = json_decode($this->oper_guide_actions, true);
                        if (($oldMonth = count($operGuideActions)) < $monthNum) {
                            for ($m = $oldMonth; $m < $monthNum; $m++) {
                                $operGuideActions[] = '待录入';
                            }
                        }
                    } else {
                        // 如果从未录入过，则组织数据返回
                        for ($month = 1; $month <= $monthNum; $month++) {
                            $operGuideActions[] = '待录入';
                        }
                    }
                    foreach ($operGuideActions as $key => $item) {
                        $month = $key+1;
                        $operGuideActionsList[] = "<strong>[{$month}个月]: </strong><br><span class='oper-action' data-uid='{$designerUid}' data-month='{$month}' data-auth_time='{$authTime}' style='cursor: pointer;color: #0c80ba;text-decoration:underline;'>{$item}</span>";
                    }

                    $operGuideActionsList = array_reverse($operGuideActionsList);
                    return '<div style="height: 130px;overflow: scroll">'.implode("<br>", $operGuideActionsList).'</div>';
                })->width(170);
            }
        );

        $tab = new Tab();
        $tab->add('账号运营辅导', $gridList->render());
        $content->row($tab);
        return $content
            ->header('账号运营辅导')
            ->breadcrumb(['text' => '设计师运营信息库'], ['text' => '账号运营辅导']);
    }

    public static function buildCondition($params) {
        $condition = [];
        // uid/昵称
        if (!empty($params['keyword'])) {
            if (is_numeric($params['keyword'])) {
                $condition['uid'] = $params['keyword'];
            } else {
                $condition['nick[~]'] = $params['keyword'];
            }
        }
        // 地区，多选
        if (!empty($params['main_area_code'])) {
            $mainAreaCode = array_filter($params['main_area_code']);
            if (!empty($mainAreaCode)) {
                $condition['main_area_code'] = $params['main_area_code'];
            }
        }
        // 当前认证阶段
        if (!empty($params['cur_stage'])) {
            $condition['cur_stage'] = $params['cur_stage'];
        }
        // 阶段任务达标情况
        if (!empty($params['cur_stage_task_done_status'])) {
            if ($params['cur_stage_task_done_status'] == self::TASK_NOT_DONE) {
                $doneStatus = [0,1];
            } else {
                $doneStatus = [1,2];
            }
            $condition['cur_stage_task_done_status'] = $doneStatus;
        }
        // 登录状态预警
        if (!empty($params['login_status'])) {
            $condition['login_status'] = $params['login_status'];
        }
        // 咨询状态预警
        if (!empty($params['consult_status'])) {
            $condition['consult_status'] = $params['consult_status'];
        }
        // 最新预估续费率
        if (!empty($params['cur_renewal_rate']['start'])) {
            $condition['cur_renewal_rate[>=]'] = $params['cur_renewal_rate']['start']*10;
        }
        if (!empty($params['cur_renewal_rate']['end'])) {
            $condition['cur_renewal_rate[<=]'] = $params['cur_renewal_rate']['end']*10;
        }
        // 累计认证时长
        if (!empty($params['total_auth_year']['start'])) {
            $condition['total_auth_year[>=]'] = number_format($params['total_auth_year']['start']*10, 0);
        }
        if (!empty($params['total_auth_year']['end'])) {
            $condition['total_auth_year[<=]'] = number_format($params['total_auth_year']['end']*10, 0);
        }
        // 对接运营
        if (!empty($params['operator_id'])) {
            $operatorId = array_filter($params['operator_id']);
            if (!empty($operatorId)) {
                $condition['operator_id'] = $params['operator_id'];
            }
        }
        return $condition;
    }

    public static function formatList(&$list) {
        foreach ($list as &$item) {
            // 获取近30天交互数
            $userLatestData = mDesignerOperateHelpPageDayCollect::getLatestCollectInfoByUid($item['uid']);
            $item['login_cnt_30'] = $userLatestData['login_cnt'];
            $item['login_status_30'] = $userLatestData['login_status'];
            $item['consult_cnt_30'] = $userLatestData['consult_cnt'];
            $item['consult_status_30'] = $userLatestData['consult_status'];
            $item['consult_unread_cnt_30'] = $userLatestData['consult_unread_cnt'];
            $item['action_cnt_30'] = $userLatestData['action_cnt'];
            $item['beaction_cnt_30'] = $userLatestData['beaction_cnt'];
        }
    }

    public static function setScript() {
        return <<<SCRIPT
        $(document).ready(function(){
            $('.oper-action').unbind('click').click(function() {
                // 获取设计师uid
                var uid = $(this).data('uid');
                // 获取月份
                var curMonth = $(this).data('month');
                // 获取运营辅导动作
                var operAction = $(this).text();
                // 认证开始时间
                var authTime = $(this).data('auth_time');
                
                layer.prompt({
                  formType: 2,
                  value: operAction,
                  title: '输入设计师UID-'+uid+'认证满'+curMonth+'个月运营辅导动作',
                  area: ['500px', '150px'] //自定义文本域宽高
                }, function(value, index, elem){
                  let url = '/admin/DesignerInfoLib/guider/saveOperAction';
                  let params = {
                    uid:uid,
                    month:curMonth,
                    oper_action:value,
                    auth_time:authTime
                  };
                  $.post(url, params, function (data) {
                    if(data.status == true) {
                        swal(data.msg, '', 'success');
                    } else {
                        swal(data.msg, '', 'error');
                    }
                  });
                  layer.close(index);
                  setTimeout(function () {
                    parent.window.location.reload();
                  }, 2000);
                });
            });
            
            // 更改任务一达标情况
            $('.task-one-select').change(function() {
                // 获取设计师uid
                var uid = $(this).data('uid');
                var taskDoneStatus = $(this).val();
                
                taskDoneStatusTxt = taskDoneStatus == 1 ? '未达标' : '达标';
                layer.confirm('是否要将设计师UID:'+uid+'的任务达标状态更改为：'+taskDoneStatusTxt+'?', {title:'提示'}, function(index) {
                  let url = '/admin/DesignerInfoLib/guider/saveTaskOneDoneStatus';
                  let params = {
                    uid:uid,
                    task_done_status:taskDoneStatus
                  };
                  $.post(url, params, function (data) {
                    if(data.status == true) {
                        swal(data.msg, '', 'success');
                    } else {
                        swal(data.msg, '', 'error');
                    }
                  });
                  layer.close(index);
                  setTimeout(function () {
                    parent.window.location.reload();
                  }, 2000);
                });
            });
        });
SCRIPT;
    }

    // 保存运营辅导动作
    public static function saveOperAction(Request $request) {
        $designerUid = $request->post('uid');
        $month = $request->post('month');
        $operAction = $request->post('oper_action');
        $authTime = $request->post('auth_time');
        $operateInfo = mOperateInfo::getInfoByUid($designerUid);
        if (empty($operateInfo)) {
            return response()->json([
                'status' => false,
                'msg' => '该设计师运营辅导信息不存在～'
            ]);
        }
        $operActions = [];
        if (empty($operateInfo['oper_guide_actions'])) {
            $diffMonth = ceil((time() - $authTime) / (30*86400));
            $monthNum = $diffMonth > 12 ? 12 : $diffMonth;
            // 如果从未录入过，则组织数据返回
            for ($m = 0; $m < $monthNum; $m++) {
                $operActions[] = '待录入';
            }
        } else {
            $operActions = json_decode($operateInfo['oper_guide_actions'], true);
        }
        if ($operActions[$month-1] == $operAction && $operAction != '待录入') {
            return response()->json([
                'status' => false,
                'msg' => '辅导动作无变化～'
            ]);
        }
        $operActions[$month-1] = $operAction;
        $newOperActions = json_encode($operActions);
        if (!mOperateInfo::updateOperGuideActions($designerUid, $newOperActions)) {
            return response()->json([
                'status' => false,
                'msg' => '运营辅导动作更新失败～'
            ]);
        }
        // 写入运营操作日志,无需判断日志是否写入成功
        mOperateLog::addLog($operateInfo['id'], self::OPER_ACTION_ASSOC_TYPE_GUIDER_ACTION, $operateInfo['oper_guide_actions'], $newOperActions, Admin::user()->id);
        return response()->json([
            'status' => true,
            'msg' => '保存成功'
        ]);
    }

    // 保存任务一达标状态
    public static function saveTaskOneDoneStatus(Request $request) {
        $designerUid = $request->post('uid');
        $taskDoneStatus = $request->post('task_done_status');
        $operateInfo = mOperateInfo::getInfoByUid($designerUid);
        if (empty($operateInfo)) {
            return response()->json([
                'status' => false,
                'msg' => '该设计师运营辅导信息不存在～'
            ]);
        }
        $stageTaskInfo = json_decode($operateInfo['stage_task_info'], true);
        foreach ($stageTaskInfo as &$item) {
            if ($item['task_no'] == self::TASK_NO_ONE) {
                $item['task_status'] = $taskDoneStatus;
                break;
            }
        }
        $stageTaskInfo = json_encode($stageTaskInfo);
        if (!mOperateInfo::updateStageTaskInfo($designerUid, $stageTaskInfo)) {
            return response()->json([
                'status' => false,
                'msg' => '任务一达标状态更新失败～'
            ]);
        }
        // 写入运营操作日志,无需判断日志是否写入成功
        mOperateLog::addLog($operateInfo['id'], self::OPER_ACTION_ASSOC_TYPE_DONE_STATUS, $operateInfo['stage_task_info'], $stageTaskInfo, Admin::user()->id);
        return response()->json([
            'status' => true,
            'msg' => '保存成功'
        ]);
    }

    public function save(Request $request, $id) {
        $name = $request->input('name', '');
        if ($name == 'sign_cnt') {
            $signCnt = $request->input('value', '');
            $operateInfo = mOperateInfo::getInfoById($id);
            if (empty($operateInfo)) {
                return response()->json([
                    'status' => false,
                    'message' => '辅导信息不存在～'
                ]);
            }
            if ($operateInfo['sign_cnt'] == $signCnt) {
                return response()->json([
                    'status' => false,
                    'message' => '无变化～'
                ]);
            }
            if (!mOperateInfo::updateSignCnt($id, $signCnt)) {
                return response()->json([
                    'status' => false,
                    'message' => '更新最新认证周期签单数失败～'
                ]);
            }
            // 写入运营操作日志,无需判断日志是否写入成功
            mOperateLog::addLog($operateInfo['id'], self::OPER_ACTION_ASSOC_TYPE_SIGN_NUM, $operateInfo['sign_cnt'], $signCnt, Admin::user()->id);
            return response()->json([
                'status' => true,
                'message' => '修改成功～'
            ]);
        }
    }
}
